/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 递归穷举
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number}
 */
var pathSum = function (root, targetSum) {
    if (root === null) return 0;

    let count = findPathSum(root, targetSum);
    count += pathSum(root.left, targetSum)
    count += pathSum(root.right, targetSum)
    return count;
};

const findPathSum = (root, sum) => {
    if (root === null) return 0
    let count = 0

    sum -= root.val
    if (sum === 0) {
        count++
    }

    count += findPathSum(root.left, sum);
    count += findPathSum(root.right, sum);

    return count
}



/**
 * 从root节点到cur节点，中间经历p1,p2...pk个节点，如果把root到每一个节点的和记录下来，作为前缀和。
 * 那么root到cur的节点和为sum，sum-targetSum如果能在前缀和中找到，那么root到pi的节点和为sum-targetSum，pi-pk的节点和为targetSum
 * 即满足题意
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number}
 */
var pathSum = function (root, targetSum) {
    let map = new Map()
    map.set(0, 1)
    return findPathSum2(root, map, 0, targetSum)
};

const findPathSum2 = (root, map, curSum, targetSum) => {
    if (root === null) return 0

    curSum += root.val;

    let count = map.get(curSum - targetSum) || 0;

    map.set(curSum, (map.get(curSum) || 0) + 1);

    count += findPathSum2(root.left, map, curSum, targetSum);
    count += findPathSum2(root.right, map, curSum, targetSum);

    // 节点和的值，例如左子树的节点和，右子树不能使用
    map.set(curSum, (map.get(curSum) || 0) - 1);

    return count
}